package org.ricks.net.action.rpc;

import org.ricks.net.action.context.session.Session;
import org.ricks.net.action.context.session.TcpSessionAdapter;
import org.ricks.net.action.parser.ProtocolParser;
import org.ricks.net.action.parser.ProtocolParserEnum;
import org.ricks.net.transport.AioSession;

import java.util.concurrent.ConcurrentHashMap;

/**
 *   rpc用于内部通信，内部通信只使用 tcp
 */
public class RpcSessionManager {

    private static final ConcurrentHashMap<AioSession, RpcClient> clientMap = new ConcurrentHashMap<>();
    public static long timeoutMillis = 1000L;
    public static ProtocolParser parser = ProtocolParserEnum.STRING.getParser();

    public static RpcClient getOrCreateClient(AioSession aioSession) {
        TcpSessionAdapter session = new TcpSessionAdapter(aioSession, parser);
        return clientMap.computeIfAbsent(aioSession, k -> new RpcClient(session, timeoutMillis));
    }

    public static RpcClient getOrCreateClient(AioSession session, ProtocolParser parser) {
        return clientMap.computeIfAbsent(session, k -> new RpcClient(new TcpSessionAdapter(session, parser), timeoutMillis));
    }

    public static void onSessionCreate(AioSession session, RpcClient client) {
        clientMap.put(session, client);
    }

    public static void onSessionClosed(AioSession session) {
        RpcClient client = clientMap.remove(session);
        if (client != null) client.close();
    }
}